//
//  LXCarSellApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/1/4.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXCarSellApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXChooseBtnTableViewCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXChooseCustomViewController.h"
#import "MoRenLianXiRenModel.h"
#import "LXApplyAnnexTableCell.h"
#import "LXChooseBrandViewController.h"
#import "PinPaiModel.h"
@interface LXCarSellApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;
@property (nonatomic) NSMutableArray *runPlatfomTypeData; // 运行平台数据源
@property (nonatomic) NSInteger runPlatfomType; // 运行平台 （1：滴滴平台，2：美团平台，3：不限平台）
@property (nonatomic) NSMutableArray *carTypeData; // 车辆类型数据源
@property (nonatomic) NSInteger carType; // 车辆类型 （1：快车优享，2：专车，3：商务）
@property (nonatomic) NSMutableArray *energeTypeData; // 能源类型数据源
@property (nonatomic) NSInteger energeType; // 能源类型（1：油车，2：电车，3：混动）
@property (nonatomic) NSMutableArray *annexAry; //  车型图片  展示用
@property (nonatomic) NSMutableArray *annexDataAry; //  车型图片 提交用
@property (nonatomic) NSString *carBrand,*carMode,*carId; // 品牌车型

@end

@implementation LXCarSellApplyViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutCustomNav:self.view title:@"发布出售"];
    self.view.backgroundColor = White_Color;
    NSDictionary *dic = @{
        @"url":@"",
    };
    self.annexAry = [NSMutableArray array];
    self.annexDataAry = [NSMutableArray array];
    [self.annexAry addObject:dic];
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerClass:[LXChooseBtnTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    [self.tableView registerClass:[LXApplyAnnexTableCell class]
         forCellReuseIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
  
    [self loadData];

    if (self.type==1) {
        [self setBottomViewWithText:@"发布"];
    }
    else if (self.type==2) {
        [self setBottomViewWithText:@"修改"];
    }
    
}




- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];

    // 运行平台 默认滴滴平台
    self.runPlatfomType = 1;
    // 车辆类型 默认快车优享受
    self.carType = 1;
    // 能源类型 默认纯电动
    self.energeType = 2;
        
    [self.loanDic setValue:self.carModel.carNum forKey:@"carNum"];
    
    // 编辑带入数据
    if (self.type==2) {
       

        // 品牌
        [self.loanDic setValue:[NSString stringWithFormat:@"%@ %@",self.carModel.carBrand,self.carModel.carMode] forKey:@"carBrand"];
        self.carId = self.carModel.ID;
        self.carBrand = self.carModel.carBrand;
        self.carMode = self.carModel.carMode;
        // 运行平台
        self.runPlatfomType = StringIsEmpty(self.carModel.runPlatfom)? 1 : [self.carModel.runPlatfom integerValue];
        // 车辆类型
        self.carType = StringIsEmpty(self.carModel.carType)? 2 : [self.carModel.carType integerValue];
        // 能源类型
        self.energeType = self.carModel.energeType == 0 ? 2 : self.carModel.energeType;
    
        // 库存
        [self.loanDic setValue:self.carModel.carNum forKey:@"carNum"];
       
      
        // 续航
        [self.loanDic setValue:self.carModel.endurance forKey:@"endurance"];
        
        // 最低价
        [self.loanDic setValue:self.carModel.floorPrice forKey:@"floorPrice"];
        // 分期期数
        [self.loanDic setValue:self.carModel.numberInstallments forKey:@"numberInstallments"];
        
    
        for (NSString *url in self.carModel.imgs) {
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,url];
            [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
            [self.annexDataAry insertObject:url atIndex:0];
        }
        
        [self.loanDic setValue:self.carModel.remark forKey:@"remark"];
        
    }
    

    self.data = @[
        @{
            @"title":@"*车型图片",
            @"key":@"annex",
            @"height":@(kComAnnexHeight)
        },
        @{
            @"title":@"品牌型号",
            @"key":@"carBrand",
            @"placeHolder" : @"请选择品牌型号",
            @"canEdit":@(NO),
            @"showAccess":self.type==2?@(NO):@(YES),
            @"maxLength":@(1000),
            @"sel":self.type==2?@"":@"clickCarBrand",
            @"height":@(kComHeight)
        },

        @{
            @"title":@"能源类型",
            @"canEdit":@(YES),
            @"key":@"energeType",
            @"height":@([LXChooseBtnTableViewCell height:self.energeTypeData])
        },
        @{
            @"title":@"车辆续航(Km)",
            @"key":@"endurance",
            @"placeHolder" : @"请输入续航公里",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"keyboardType":@(UIKeyboardTypeDecimalPad),
            @"maxLength":@(1000),
            @"maxNum":@(999),
            @"sel":@"",
            @"height":@(kComHeight)
        },

        @{
            @"title":@"运行平台",
            @"canEdit":@(YES),
            @"key":@"runPlatfom",
            @"height":@([LXChooseBtnTableViewCell height:self.runPlatfomTypeData])
        },
        @{
            @"title":@"车辆类型",
            @"canEdit":@(YES),
            @"key":@"carType",
            @"height":@([LXChooseBtnTableViewCell height:self.carTypeData])
        },

        @{
            @"title":@"库存数量(辆)",
            @"key":@"carNum",
            @"placeHolder" : @"请输入库存数量",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"keyboardType":@(UIKeyboardTypeNumberPad),
            @"maxLength":@(8),
            @"maxNum":@(999),
            @"sel":@"",
            @"height":@(kComHeight)
        },

        @{
            @"title":@"首付款(万元/起)",
            @"key":@"floorPrice",
            @"placeHolder" : @"请输入最低首付金额",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"keyboardType":@(UIKeyboardTypeDecimalPad),
            @"maxLength":@(8),
            @"maxNum":@(100),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"可分期数(期)",
            @"key":@"numberInstallments",
            @"placeHolder" : @"请输入分期期数",
            @"canEdit":@(YES),
            @"showAccess":@(NO),
            @"keyboardType":@(UIKeyboardTypeNumberPad),
            @"maxLength":@(8),
            @"maxNum":@(60),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"备注",
            @"key":@"remark",
            @"height":@(150)
        },

       
 ].mutableCopy;
    
    
    [self.tableView reloadData];
   
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        return [LXApplyAnnexTableCell getCellHeightWithDataSource:self.annexAry] + 50;
    }
    
    if ([dic[@"key"] isEqualToString:@"endurance"]) {
        if (self.energeType == 1) {
            return 0.00001;
        }
    }
    
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];
    
    // 车辆图片
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        LXApplyAnnexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = dic[@"title"];
        [cell reloadAnnexData:self.annexAry WithMaxNum:5];
        
        
        
        // 添加图片
        [cell setCallBackTakeAnnex:^(NSInteger num) {
            [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(NSDictionary *dic) {
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,dic[@"url"]];
                [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
                
                [self.annexDataAry insertObject:dic[@"url"] atIndex:0];
                
                [self.tableView reloadData];
            }];
        }];
        
        
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            UIImageView *imageV = (UIImageView*)obj;
            UIWindow *window = [BaseViewController getCurrentWindow];
            ShowBigImageWithFrameView *ImageShow = [[ShowBigImageWithFrameView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, B_HEIGHT) withImage:imageV.image];
            [window addSubview:ImageShow];
            
        }];
        // 删除图片
        [cell setCallBackDeleteAnnex:^(NSInteger num) {
            
            [self.annexAry removeObjectAtIndex:num];
            [self.annexDataAry removeObjectAtIndex:num];

            [self.tableView reloadData];
        }];
        
        
        return cell;
    }

    else if ([dic[@"key"] isEqualToString:@"runPlatfom"]||
             [dic[@"key"] isEqualToString:@"carType"]||
             [dic[@"key"] isEqualToString:@"energeType"]||
             [dic[@"key"] isEqualToString:@"depost"]) {
       
        
        NSArray *tempAry;
        if ([dic[@"key"] isEqualToString:@"runPlatfom"]) {
            tempAry = self.runPlatfomTypeData;
        }
        else if ([dic[@"key"] isEqualToString:@"carType"]) {
            tempAry = self.carTypeData;
        }
        else if ([dic[@"key"] isEqualToString:@"energeType"]) {
            tempAry = self.energeTypeData;
        }
      
        
       LXChooseBtnTableViewCell *cell = [[LXChooseBtnTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class]) WithData:tempAry];

       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
        cell.canEdit = dic[@"canEdit"];
       cell.titleLab.text = dic[@"title"];
       [cell setClickBtnBlock:^(NSInteger Id) {
           if ([dic[@"key"] isEqualToString:@"runPlatfom"]) {
               self.runPlatfomType = Id;
           }
           else if ([dic[@"key"] isEqualToString:@"carType"]) {
               self.carType = Id;
           }
           else if ([dic[@"key"] isEqualToString:@"energeType"]) {
               self.energeType = Id;
               [self.tableView reloadData];
           }
          
       }];
       
       return cell;
    }
    // 备注
    if([dic[@"key"]  isEqualToString:@"remark"]){
       LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
       cell.textView.placeholder = @"请输入 ~";
       cell.textView.maxLength = 200;
       cell.remarkTitle.text = dic[@"title"];
       cell.textView.text = self.loanDic[dic[@"key"]];
       [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
           self.loanDic[dic[@"key"]]  = textStr;
       }];
       return cell;
   }
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.swicth.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    if ([dic[@"key"] isEqualToString:@"carBrand"] && !StringIsEmpty(self.loanDic[dic[@"key"]])) {
        cell.textFiled.hidden = YES;
        cell.subTitleLab.hidden = NO;
        cell.subTitleLab.text = self.loanDic[dic[@"key"]];
    }
    
    
    
  
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}


- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, kScreenHeight - kViewTopHeight - kComHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(void)clickBottomView:(UIButton *)sender{
    
    if (self.annexDataAry.count==0) {
        showAlert(@"请上传车辆图片");
        return;
    }
    
    if (StringIsEmpty(self.carBrand)){
        showAlert(@"品牌型号不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"endurance"]) && self.energeType != 1){
        showAlert(@"续航不能为空");
        return;
    }
    if ([self.loanDic[@"endurance"] doubleValue] < 300 && self.energeType != 1){
        showAlert(@"续航不能低于300Km");
        return;
    }
    if ([self.loanDic[@"carNum"] doubleValue] < 1){
        showAlert(@"库存不能低于1辆");
        return;
    }
    if ([self.loanDic[@"floorPrice"] doubleValue] < 1){
        showAlert(@"首付不能低于1万元");
        return;
    }
    if ([self.loanDic[@"numberInstallments"] intValue] == 0){
        showAlert(@"请输入分期数");
        return;
    }
    

    NSString *imgsJson = [NSString toJSONData:self.annexDataAry];
    NSMutableDictionary *dic = @{
        @"carBrandId":self.carId, // 所属车辆id
        @"brand":self.carBrand, // 车辆品牌
        @"model":self.carMode,// 车辆型号
        @"carNum":self.loanDic[@"carNum"],// 库存
        @"carType":@(self.carType),// 车辆类型
        @"runPlatfom":@(self.runPlatfomType), // 运行品台
        @"energeType":@(self.energeType),//能源类型
        @"endurance":self.loanDic[@"endurance"],// 续航
        @"floorPrice":self.loanDic[@"floorPrice"],// 最低价
        @"numberInstallments":self.loanDic[@"numberInstallments"],//分期期数
        @"imgs":imgsJson,// 图片
        @"type":@"2",// 1出租2出售
        @"remark":self.loanDic[@"remark"]
    }.mutableCopy;

    if (self.type == 2) {
        [dic setValue:self.carId forKey:@"id"];
        [dic removeObjectForKey:@"carBrandId"];
    }

    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
       } commitHandlerBlock:^{
           
           NSString *url = POST_SaveCar_URL;
           if (self.type==2||self.type == 3) {
               url = POST_PostEditCarData;
           }
           
           [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
               if (isSuccess) {
                   showAlert(@"发布成功");
                   kUserDefaultSetBool(YES, kRefreshStr);
    
                   [self pop];
               }
           } failure:^(NSUInteger code, NSString * _Nonnull message) {
               
           } withShowHud:YES];

           
       } onVC:self];

    
    
   
    
}
#pragma mark --  能源类型数据源
- (NSArray *)energeTypeData{
    

    
    NSArray *energeTypeAry = [[NSUserDefaults standardUserDefaults] valueForKey:k_NYLX];
    
    _energeTypeData = [NSMutableArray array];

    if (!ObjectIsEmpty(energeTypeAry)) {
        
        for (int i = 0; i<energeTypeAry.count; i++) {
            
            NSDictionary *mm = energeTypeAry[i];
            NSDictionary *dic = @{
                @"title":mm[@"label"],
                @"sel":@(NO),
                @"id":mm[@"value"],
            }.mutableCopy;
            [_energeTypeData addObject:dic];
        }
    }

    for (NSMutableDictionary *dic in _energeTypeData) {
        if ([dic[@"id"] intValue]==self.energeType) {
            [dic setValue:@(YES) forKey:@"sel"];
            break;
        }
    }
    return _energeTypeData;
    
   
}
#pragma mark -- 车辆类型数据源
- (NSArray *)carTypeData{
    
    
    NSArray *carTypeAry = [[NSUserDefaults standardUserDefaults] valueForKey:k_CLLX];
    
    _carTypeData = [NSMutableArray array];

    if (!ObjectIsEmpty(carTypeAry)) {
        
        for (int i = 0; i<carTypeAry.count; i++) {
            
            NSDictionary *mm = carTypeAry[i];
            NSDictionary *dic = @{
                @"title":mm[@"label"],
                @"sel":@(NO),
                @"id":mm[@"value"],
            }.mutableCopy;
            [_carTypeData addObject:dic];
        }
    }

    for (NSMutableDictionary *dic in _carTypeData) {
        if ([dic[@"id"] intValue]==self.carType) {
            [dic setValue:@(YES) forKey:@"sel"];
            break;
        }
    }
    return _carTypeData;
}
#pragma mark -- 运行平台数据源
- (NSArray *)runPlatfomTypeData{
    
    
    NSArray *operPlatformAry = [[NSUserDefaults standardUserDefaults] valueForKey:k_YXPT];
    
    _runPlatfomTypeData = [NSMutableArray array];

    if (!ObjectIsEmpty(operPlatformAry)) {
        
        for (int i = 0; i<operPlatformAry.count; i++) {
            
            NSDictionary *mm = operPlatformAry[i];
            NSDictionary *dic = @{
                @"title":mm[@"label"],
                @"sel":@(NO),
                @"id":mm[@"value"],
            }.mutableCopy;
            [_runPlatfomTypeData addObject:dic];
        }
    }
    
 
    for (NSMutableDictionary *dic in _runPlatfomTypeData) {
        if ([dic[@"id"] intValue] == self.runPlatfomType) {
            [dic setValue:@(YES) forKey:@"sel"];
            break;
        }
    }
    return _runPlatfomTypeData;
}
#pragma mark -- 选择车辆品牌
- (void)clickCarBrand{
    
    LXChooseBrandViewController *vc = [[LXChooseBrandViewController alloc] init];
    [vc setToSendValue:^(PinPaiChildrenModel * _Nonnull model) {
       
        [self.loanDic setValue:[NSString stringWithFormat:@"%@ %@",model.parent,model.value] forKey:@"carBrand"];
        self.carBrand = model.parent;
        self.carMode = model.value;
        self.carId = model.ID;
        [self.tableView reloadData];
    }];
    [self pushToNextController:vc];
}

- (void)pop{
    if (self.type == 2 && !StringIsEmpty(self.fromVc)) {
        for (UIViewController *controler in self.navigationController.viewControllers) {
            if ([controler isKindOfClass:NSClassFromString(self.fromVc)]) {
                [self.navigationController popToViewController:controler animated:YES];
                return;
            }
        }
    }
    else if(!StringIsEmpty(self.fromVc)) {
        [self backToVC:self.fromVc];
    }
    else {
        [super pop];
    }
}

@end
